package com.wa.publishConfirm;

import com.rabbitmq.client.Channel;
import com.wa.util.RabbitUtils;

/**
 * 发布确认
 *
 * @Notes
 * @Author gary
 * @Date 2021/12/5 14:17
 **/
public class Single {
    public static void main(String[] args) throws Exception {
        publishMessageIndividually();
    }

    public static void publishMessageIndividually() throws Exception {
        try (Channel channel = RabbitUtils.getChannel()) {
            String queueName = "publish";
            channel.queueDeclare(queueName, false, false, false, null);
            //开启发布确认
            channel.confirmSelect();
            long begin = System.currentTimeMillis();
            for (int i = 0; i < 1000; i++) {
                String message = i + "";
                channel.basicPublish("", queueName, null, message.getBytes());
                //服务端返回 false 或超时时间内未返回，生产者可以消息重发
                boolean flag = channel.waitForConfirms();
                if (flag) {
                    System.out.println("消息发送成功");
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("发布" + 1000 + "个单独确认消息,耗时" + (end - begin) +
                    "ms");
        }
    }
}
